import { queryProjectTree } from '@/api/list/project-list';
import { onMounted, ref } from 'vue';
import type { ShowSearchType } from 'ant-design-vue/es/cascader';
import { localStorage } from '@/utils/local-storage';
import type { Pagination, TableFilters } from '@/typing';
import { useResizeObserver } from '@vueuse/core';

export default function useProjectCondition(queryParams, fetchDataContext, noDeleteKey = []) {
    const treeData = ref<any[]>([]);
    const tableListWrapRef = ref();
    const tableHeight = ref(300);
    const filter: ShowSearchType['filter'] = (inputValue, path) => {
        return path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    };
    const queryTreeData = () => {
        queryProjectTree().then(build => {
            treeData.value = [build.data];
        });
    };

    const handleTableChange = ({ current, pageSize }: Pagination, filters?: TableFilters) => {
        fetchDataContext.current = current;
        fetchDataContext.pageSize = pageSize;
    };

    const handleSearch = () => {
        fetchDataContext.current = 1;
        fetchDataContext.requestParams = {
            ...queryParams,
        };
        fetchDataContext.executeImmediately = true;
    };
    const handleReset = () => {
        Object.keys(queryParams).map((item: string) => {
            if (![...noDeleteKey].includes(item)) delete queryParams[item];
        });
        fetchDataContext.current = 1;
        fetchDataContext.requestParams = { ...queryParams };
    };

    const handleTreeCheck = (data: any, treeData: any[], checkedKeys: string[]) => {
        queryParams.propertyId = data.buildSelectedCode.join(',');
        queryParams.projectCodes = data.projectCode;
        queryParams.projectCode = data.projectCode.at(-1);
        fetchDataContext.executeImmediately = true;

        handleSearch();
    };

    onMounted(async () => {
        useResizeObserver(tableListWrapRef, ([{ target }]) => {
            tableHeight.value = target.clientHeight;
        });
        // queryTreeData();
    });

    return {
        filter,
        treeData,
        tableListWrapRef,
        tableHeight,

        queryTreeData,
        handleTreeCheck,
        handleSearch,
        handleReset,
        handleTableChange,
    };
}
